<template>
  <div class="gap-col-8 px-4 pt-2">
    <div class="font-size-14 font-weight-500 line-height-125">
      <i18n-t keypath="search.result.creators" tag="div">
        <template #keyword>
          <span class="text-primary">{{ searchText }}</span>
        </template>
        <template #num>
          <span>{{ result.creator_total }}</span>
        </template>
      </i18n-t>
    </div>
    <CreatorRow
      :items="dataList"
      :loading="loading"
      :no-more="noMore"
      @intersect="nextPage"
      @click:item="onCreatorClick"
    ></CreatorRow>
  </div>
</template>
<script setup>
import { onActivated, watch } from 'vue'
import { storeToRefs } from 'pinia'
import { useSearchResultStore, useSearchStore } from '@/store/search'
import CreatorRow from '@/components/search/row/CreatorRow.vue'
import { useInfinite } from '@/compositions/request/infinite'
import { trackEvent } from '@/gtm'
import API from '@/http'

const searchStore = useSearchStore()
const { toCreatorViewer } = searchStore

const searchResultStore = useSearchResultStore()
const { result, searchText, hasSearchText } = storeToRefs(searchResultStore)

const creatorLimit = import.meta.env.VITE_CREATOR_LIST_LIMIT ?? 12
const { dataList, loading, noMore, nextPage, refresh } = useInfinite({
  request: API.Media.creators,
  params: hasSearchText.value ? { keyword: searchText.value } : {},
  limit: creatorLimit,
})

onActivated(async () => {
  trackEvent({ key: 35, value: null, meta: { keyword: searchText.value } })
})

watch(searchText, (keyword) => {
  if (!hasSearchText.value) {
    return
  }
  refresh({ newParams: { keyword } })
})

function onCreatorClick(aff, username) {
  toCreatorViewer(aff, username)
  trackEvent({ key: 36, value: null, meta: { aff } })
}
</script>
